package com.bigflexlib.mouse {
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	
	import mx.core.UIComponent;

    [Event(type="com.bigflexlib.mouse.DragDetectorEvent", name="dragOff")]
	public class DragDetector extends EventDispatcher
	{
		public static var THRESHOLD_DISTANCE:int = 5;
		private var component:UIComponent;
		private var isButtonDown:Boolean = false;
		private var mouseDownX:int;
		private var mouseDownY:int;
		
		public function DragDetector(component:UIComponent)
		{
			this.component = component;
			component.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
			component.addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
			component.addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
		}

		private function handleMouseUp(event:MouseEvent):void
		{
			isButtonDown = false;
		}

		private function handleMouseDown(event:MouseEvent):void
		{
			isButtonDown = true;
			mouseDownX = event.stageX;
			mouseDownY = event.stageY;			
		}

		private function handleMouseMove(event:MouseEvent):void
		{
			if (!isButtonDown)
				return;
			if (!event.buttonDown)
			{
				isButtonDown = false;
				return;
			}		   
			if (distance(mouseDownX, mouseDownY, event.stageX, event.stageY) >
				THRESHOLD_DISTANCE)
			{
				dispatchEvent(new DragDetectorEvent());
			}
		}

		private static function distance(x0:int, y0:int, x1:int, y1:int):Number
		{
			var dx:int = x1 - x0;
			var dy:int = y1 - y0;
			return Math.sqrt(dx * dx + dy * dy);
		}
	}
}